<template>
	<view class="post">
		<view class="post-item" v-for="(item,index) in list" :key="item.id" @click="onDetail(item,false)">
			<!-- 用户信息区域 -->
			<view class="level">
				<view class="level-left" @click.stop="toHomePage(item)">
					<u-avatar class="avatar" mode="aspectFill" :class="item.avatar?'':'avatar-b'" :src="item.avatar"
						size="35"></u-avatar>
					<view class="level-left-name">
						<view class="name">{{item.nickName}}</view>
						<view class="date" v-if="current!=0">{{item.createTime}}</view>
					</view>
				</view>
				<!-- 关注按钮 -->
				<view v-if="shouldShowFollowButton(item)" class="level-right" :class="{active: item.isFollowed==1}"
					@click.stop="onFollow(item,index)">
					<u-icon :name="item.isFollowed==0?'plus':'checkmark'" class="icon" :plain="true" size="14"
						shape="circle" :color="item.isFollowed==0?'#FE4E4E':'#ccc'"></u-icon>
					{{item.isFollowed==0?'关注':'已关注'}}
				</view>
			</view>

			<!-- 内容区域 -->
			<post-shrink :text="item.content" :line="3" />

			<!-- 媒体内容区域 -->
			<view class="album" @click.stop>
				<!-- 视频内容 -->
				<!-- #ifdef APP-PLUS || H5 -->
				<view :class="'video-container-' + item.id" v-if="hasVideo(item)">
					<DomVideoPlayer :class="'video-'+index" :ref="'allPostRef'+item.id"
						@click.native.stop="openCustomFullScreenVideo(item.id, item.files[0].fileUrl)"
						@videoDidExitFullScreen="$emit('videoDidExitFullScreen')" :src="item.files[0].fileUrl" loop
						:muted="true" :autoplay="false" :isLoading="true"
						style="max-width: 600rpx;width:400rpx;max-height: 600rpx;" />
				</view>
				<!-- #endif -->

				<!-- 田字格图片布局 -->
				<view v-if="isTianziGrid(item)" class="grid-tianzi">
					<view v-for="(file, fileIndex) in item.files" :key="fileIndex" class="grid-tianzi-item"
						@click.stop="previewImage(item.files, fileIndex)">
						<image style="width: 117px;height: 117px;" :src="getFileDisplayUrl(file)" :lazy-load="true"
							mode="aspectFill" @error="onGridImageError(fileIndex)"
							@load="onGridImageLoad(item, fileIndex)" :class="getImageClass(item, fileIndex)">
						</image>
					</view>
				</view>

				<!-- 普通图片布局 -->
				<custom-album v-else-if="hasImages(item)" :urls="item.files" image-url-key="fileUrlCached"
					@click.native.stop="previewFromCustomAlbum(item.files)">
				</custom-album>

				<!-- 位置信息 -->
				<view v-if="item.location" class="post-dw">
					<u-icon name="map" color="#666" size="22"></u-icon>
					<view class="single-line">
						{{getLocation(item.location)}}
					</view>
				</view>
			</view>

			<!-- 操作按钮区域 -->
			<common-post-actions :data="item" @onDetail="onDetail(item, true)"></common-post-actions>
		</view>
		<!-- 全屏视频模态框 -->
		<!-- #ifdef APP-PLUS || H5 -->
		<VideoFullscreenModal :visible="showVideoModal" :video-src="currentModalVideoSrc"
			@close="closeCustomFullScreenVideo" />
		<!-- #endif -->
	</view>
</template>

<script>
	import PostShrink from "@/components/post-shrink/post-shrink.vue";
	import CComment from "@/components/XJ-comment/index.vue";
	// #ifdef APP-PLUS || H5
	import DomVideoPlayer from '@/components/DomVideoPlayer/DomVideoPlayer.vue';
	import VideoFullscreenModal from '@/components/VideoFullscreenModal/VideoFullscreenModal.vue';
	// #endif
	import {
		getClientFollow
	} from '@/request/api.js';
	import CustomAlbum from '@/components/custom-album/custom-album.vue';
	import commonPostActions from '@/components/common-post-actions/common-post-actions.vue';
	export default {
		name: "common-post",
		props: {
			list: {
				type: Array,
				default: () => []
			},
			current: {
				type: Number,
				default: null
			}
		},
		components: {
			PostShrink,
			CComment,
			CustomAlbum,
			commonPostActions,
			// #ifdef APP-PLUS || H5
			DomVideoPlayer,
			VideoFullscreenModal
			// #endif
		},
		data() {
			return {
				windowHeight: 0,
				observers: {},
				videoPlayers: {},
				showVideoModal: false,
				currentModalVideoSrc: '',
				currentModalVideoId: null,
				imageLoadedStates: {},
			}
		},
		watch: {
			list: {
				handler(newList) {
					this.$nextTick(() => {
						this.cleanupAllObservers();
						this.initializeVideoObservers();
					});
				},
				deep: true,
				immediate: true
			}
		},

		mounted() {
			const systemInfo = uni.getSystemInfoSync();
			this.windowHeight = systemInfo.windowHeight;
		},
		beforeDestroy() {
			this.cleanupAllObservers();
		},
	
		methods: {
			// 条件判断方法
			shouldShowFollowButton(item) {
				return item.isFollowed != null && item.userId !== this.$store.state.userInfo.userId;
			},

			hasVideo(item) {
				return item.files && item.files.length > 0 && item.files[0].isImage === 0;
			},

			hasImages(item) {
				return item.files && item.files.length > 0 && item.files[0].isImage === 1;
			},

			isTianziGrid(item) {
				return item.files && item.files.length === 4 && item.files[0].isImage === 1;
			},

			getLocation(str) {
				if (!str) return '';
				const index = str.indexOf('-');
				return index !== -1 ? str.substring(index + 1) : str;
			},

			getFileDisplayUrl(file) {
				return file.previewImgUrl || file.fileUrl || '';
			},

			getImageKey(item, fileIndex) {
				return `${item.id}_${fileIndex}`;
			},

			getImageClass(item, fileIndex) {
				const key = this.getImageKey(item, fileIndex);
				return {
					'img-loading': !this.imageLoadedStates[key],
					'img-loaded': this.imageLoadedStates[key]
				};
			},

			onGridImageError(fileIndex) {
				console.warn(`Grid image at index ${fileIndex} failed to load`);
			},

			onGridImageLoad(item, fileIndex) {
				const key = this.getImageKey(item, fileIndex);
				this.$set(this.imageLoadedStates, key, true);
			},

			previewImage(originalFiles, currentIndex) {
				const urls = originalFiles.map(file => this.getFileDisplayUrl(file));
				const validUrls = urls.filter(url => url && typeof url === 'string' && url.length > 0);

				if (validUrls.length === 0) {
					console.warn('没有有效的图片URL用于预览');
					return;
				}

				uni.previewImage({
					urls: validUrls,
					current: currentIndex,
					fail: (err) => {
						console.error('图片预览失败:', err);
					}
				});
			},

			previewFromCustomAlbum(originalFiles) {
				if (originalFiles?.length > 0) {
					this.previewImage(originalFiles, 0);
				}
			},

			initializeVideoObservers() {
				if (!this.list || this.list.length === 0) return;

				this.list.forEach((item) => {
					if (this.hasVideo(item)) {
						this.setupVideoObserver(item);
					}
				});
			},

			setupVideoObserver(item) {
				const videoContainerClass = `.video-container-${item.id}`;
				const videoPlayerRefName = `allPostRef${item.id}`;

				this.$nextTick(() => {
					const videoPlayerArray = this.$refs[videoPlayerRefName];
					if (!videoPlayerArray?.[0]) {
						console.warn(`Video player ref ${videoPlayerRefName} not found for item ${item.id}`);
						return;
					}

					this.videoPlayers[item.id] = videoPlayerArray[0];
					this.cleanupObserverForItem(item.id);

					const observer = uni.createIntersectionObserver(this, {
						thresholds: [0.5],
						initialRatio: 0
					});

					observer.relativeToViewport({
							top: '0px',
							bottom: '0px'
						})
						.observe(videoContainerClass, (res) => {
							this.handleVideoVisibilityChange(item.id, res);
						});

					this.observers[item.id] = observer;
				});
			},

			handleVideoVisibilityChange(itemId, res) {
				const player = this.videoPlayers[itemId];
				if (!player) return;

				if (res?.intersectionRatio >= 0.5) {
					player.play();
				} else {
					player.pause();
				}
			},

			cleanupObserverForItem(itemId) {
				if (this.observers[itemId]) {
					this.observers[itemId].disconnect();
					delete this.observers[itemId];
				}
				if (this.videoPlayers[itemId]) {
					this.videoPlayers[itemId].pause?.();
					delete this.videoPlayers[itemId];
				}
			},

			cleanupAllObservers() {
				Object.keys(this.observers).forEach(itemId => {
					this.observers[itemId].disconnect();
				});
				this.observers = {};

				Object.values(this.videoPlayers).forEach(player => {
					player?.pause?.();
				});
				this.videoPlayers = {};
			},

			openCustomFullScreenVideo(itemId, videoUrl) {
				this.pauseVideoById(itemId);
				this.currentModalVideoSrc = videoUrl;
				this.currentModalVideoId = itemId;
				this.showVideoModal = true;
			},

			closeCustomFullScreenVideo() {
				this.showVideoModal = false;
				this.currentModalVideoSrc = '';
				this.currentModalVideoId = null;
			},

			pauseVideoById(itemId) {
				this.videoPlayers[itemId]?.pause?.();
			},

			setFollow(userId, newFollowStatus) {
				this.list.forEach((post, i) => {
					if (post.userId === userId) {
						this.$set(this.list[i], 'isFollowed', newFollowStatus ? 1 : 0);
					}
				});
			},

			async onFollow(item, indexInList) {
				const currentFollowStatus = item.isFollowed;
				const targetFollowStatus = currentFollowStatus === 0 ? 1 : 0;

				// 立即更新UI
				this.setFollow(item.userId, targetFollowStatus === 1);

				try {
					await getClientFollow({
						userId: item.userId
					});
					// 请求成功，UI状态已更新，无需额外操作
				} catch (error) {
					// 请求失败，恢复之前的状态
					this.setFollow(item.userId, currentFollowStatus === 1);
					uni.showToast({
						title: targetFollowStatus === 1 ? "关注失败" : "取消关注失败",
						icon: 'none',
					});
				}
			},

			toHomePage(item) {
				const initialData = {
					userId: item.userId,
					isFollowed: item.isFollowed === 1
				};

				uni.navigateTo({
					url: '/pages_sub/user/others/others',
					events: {
						returnData: (returnedData) => {
							if (returnedData.userId === item.userId && returnedData.isFollowed !== undefined) {
								this.setFollow(returnedData.userId, returnedData.isFollowed);
							}
						}
					},
					success: (res) => {
						res.eventChannel.emit('sendInitData', {
							data: JSON.stringify(initialData)
						});
					}
				});
			},

			onDetail(item, scroll = false) {
				this.$emit('detailClick', item);
			},
		}
	}
</script>

<style lang="scss" scoped>
	::v-deep .u-album__row__wrapper__text {
		background-color: rgba(0, 0, 0, 0.7);
	}

	::v-deep .u-text__value {
		font-size: 60rpx;
	}

	.video-container {
		width: auto;
		height: auto;
	}

	.video {
		object-fit: cover;
		position: relative;
		will-change: transform;
		transform: translateZ(0);
	}

	.post {
		background-color: #F8F8F8;

		.post-item {
			background-color: #FFFFFF;
			position: relative;
			padding: 10rpx 40rpx 0 40rpx;
			margin-bottom: 20rpx;
			overflow: hidden;
		}

		.avatar {
			width: 100rpx;
			height: 100rpx;
			border-radius: 50%;
		}

		.level-left-name {
			margin-left: 20rpx;
		}

		.avatar-b {
			border: 1rpx solid #FFAE1A;
		}

		.album {
			width: 100%;
			display: inline-block;
			margin-top: 15rpx;
			position: relative;
			z-index: 1;
			padding-bottom: 40rpx;
			border-bottom: 1rpx solid #F4F4F4;

			.grid-tianzi {
				display: grid;
				width: 424rpx;
				grid-template-columns: repeat(2, 1fr);
				grid-auto-rows: 1fr;
				gap: 4px;

				.grid-tianzi-item {
					width: 212rpx;
					aspect-ratio: 1 / 1;
					overflow: hidden;
				}
			}
		}

		.level {
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-bottom: 15rpx;
			padding: 15rpx 0;

			.level-left {
				display: flex;
				align-items: center;
				z-index: 9;
			}

			.level-right {
				display: flex;
				color: #FE4E4E;
				border: 1rpx solid #FE4E4E;
				border-radius: 50rpx;
				font-size: 26rpx;
				padding: 5rpx 15rpx;
				transition: all 0.3s ease;

				.icon {
					margin-right: 5rpx;
				}

				&.active {
					color: #cccccc;
					border: 1rpx solid #cccccc;
				}
			}
		}

		.name {
			font-size: 32rpx;
			font-weight: 500;
		}

		.date {
			color: #787878;
			font-size: 22rpx;
			margin-top: 5rpx;
		}
	}

	.post-dw {
		color: #494A53;
		min-width: 130rpx;
		margin-right: 20rpx;
		margin-top: 20rpx;
		display: flex;
		align-items: center;
		font-size: 28rpx;

		.single-line {
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
			max-width: 500rpx;
		}
	}

	/* 图片加载状态样式 */
	.img-loading {
		opacity: 0.5;
		transition: opacity 0.3s ease;
	}

	.img-loaded {
		opacity: 1;
		transition: opacity 0.3s ease;
	}
</style>